﻿#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include <stdlib.h>

//Definition for singly-linked list.
struct ListNode 
{
    int val;
    struct ListNode *next;
};
 
struct ListNode* removeElements(struct ListNode* head, int val)
{
    struct ListNode* cur = head;
    struct ListNode* prev = NULL;
    while (cur && cur->val == val)//ͷɾ
    {
        prev = cur;
        cur = cur->next;
        free(prev);
    }
    head = cur;

    if (!cur)
    {
        return head;
    }

    while (cur->next != NULL)
    {
        if (cur == NULL)
        {
            break;
        }
        if (cur->next->val == val)
        {
            prev = cur->next;
            cur->next = cur->next->next;
            free(prev);
        }
        else
        {
            cur = cur->next;
        }
    }


    return head;
}

int main()
{
    //struct ListNode* n1 = (struct ListNode*)malloc(16);
    //int n = sizeof(struct ListNode);
    //printf("%d\n", n);
    //struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));

    struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode)); 
    struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));
    n1->val = 1;
    n2->val = 7;
    n3->val = 7;
    n4->val = 6;
    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = NULL;

    removeElements(n1, 7);

    return 0;
}